package top.fyukina.fyson.runtime.loader;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONException;
import com.alibaba.fastjson2.JSONObject;
import top.fyukina.fyson.runtime.exception.FysonException;
import top.fyukina.fyson.runtime.exception.SyntaxException;
import top.fyukina.fyson.runtime.exception.VersionException;

public final class JSONLoader {
    public static final double version = 1.1;
    private JSONLoader() {}
    public static void load(String content) throws FysonException {
        try {
            JSONObject o = JSON.parseObject(content);
            double v = o.getDoubleValue("version");
            if (v > version || Math.floor(v) != Math.floor(version))
                throw new VersionException();
            loadScript(o.getJSONArray("scripts"));
        } catch (JSONException e) {
            throw new SyntaxException("JSON format error: " + e.getMessage());
        }
    }
    public static void loadScript(JSONArray scripts) throws FysonException {
        if (scripts == null) return ;
        for (int i = 0; i < scripts.size(); i++) {
            JSONObject o = scripts.getJSONObject(i);
            String cmd = o.getString("cmd");
            if (cmd == null) throw new SyntaxException("No specific command");
            if (ValueLoader.ifLoad(o.getJSONArray("if")))
                CmdLoader.load(cmd, o.get("arg"));
        }
    }
}